package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.UserDao;
import com.mozz.finally_work.pojo.User;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import sun.misc.BASE64Encoder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nickName = request.getParameter("nickName");
        String password = request.getParameter("password");

        // 密码md5加密
        MessageDigest md = null;
        String newPassword = null;
        try {
            md = MessageDigest.getInstance("MD5");
            BASE64Encoder encoder = new BASE64Encoder();
            newPassword = encoder.encode(md.digest(password.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 登录校验
        SqlSession session = MybatisUtils.getSession();
        UserDao dao = session.getMapper(UserDao.class);
        User user = dao.login(nickName, newPassword);
        session.close();

        // 存放到Session中
        HttpSession requestSession = request.getSession();
        requestSession.setAttribute("user", user);
        // 重定向
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        response.sendRedirect("index.jsp");
    }
}
